//
//  AdController.m
//  AoA
//
//  Created by abaca on 2010/9/12.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import <SystemConfiguration/SystemConfiguration.h>
#import "AdController.h"
#import "Advert.h"
#import "Connectivity.h"

//#include <sqlite3.h>

static NSString *kCname   = @"cname";
static NSString *kTeacher = @"teacher";
static NSString *kCdate   = @"cdate";
static NSString *kCtime   = @"ctime";
static NSString *kFee     = @"fee";
static NSString *kAddress = @"address";
static NSString *kRemark  = @"remark";
static NSString *kContact = @"contact";
static NSString *kEmail   = @"email";

#if TARGET_IPHONE_SIMULATOR
	//static NSString *baseURL = @"http://10.2.2.224/bonus/aoa.txt";
	static NSString *baseURL = @"http://www.aoa.co/rod/alert.php";
#else
	static NSString *baseURL = @"http://www.aoa.co/rod/alert.php";
#endif

//#define baseURL   @"http://10.2.2.224/bonus/aoa.txt"
//#define baseURL   @"http://www.aoa.co/rod/alert.php"

@implementation AdController


#pragma mark -
#pragma mark Database

/*
-(void) initDB {
	
	theAds    = [[NSMutableArray alloc] init];
	theTitles = [[NSMutableArray alloc] init];
	
	char			*sqlStmt;
	sqlite3			*db;
	char			*dbName;
	sqlite3_stmt	*stmt;
	
	const char *sql = "select locate from ad group by locate order by locate";
	dbName = (char *)[[[NSBundle mainBundle] pathForResource:@"mydatabase" ofType:@"sqlite"] UTF8String];
	
	if (sqlite3_open(dbName, &db)==SQLITE_OK) {
		
		sqlStmt = sqlite3_mprintf(sql);
		
		if (sqlite3_prepare_v2(db, sqlStmt, -1, &stmt, NULL)==SQLITE_OK) {
			
			while (sqlite3_step(stmt) == SQLITE_ROW) {

				[theTitles addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 0)]];
				
				char			*sqlStmt_Ad;
				sqlite3_stmt	*stmt_Ad;

				//NSLog(@"%@", [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 0)]);
				NSString *str = [NSString stringWithFormat:@"select * from ad where actived='TRUE' and locate='%@' order by cdate desc",
									[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 0)]];
				const char *sql_Ad = [str UTF8String];
				
				sqlStmt_Ad = sqlite3_mprintf(sql_Ad);
				
				if(sqlite3_prepare_v2(db, sqlStmt_Ad, -1, &stmt_Ad, NULL)==SQLITE_OK) {
					NSMutableArray *theGroups = [[[NSMutableArray alloc] init] autorelease];
					
					while (sqlite3_step(stmt_Ad) == SQLITE_ROW) {
						//NSLog(@"%@", [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 3)]);
						//[theGroups addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 3)]];
						
						[theGroups addObject:[NSDictionary dictionaryWithObjectsAndKeys:
											   [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 3)], kCname,
											   [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 2)], kTeacher,
											   [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 4)], kCdate,
											   [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 5)], kCtime,
											   [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 6)], kFee,
											   [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 7)], kAddress,
											   [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 8)], kRemark,
											   [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 9)], kContact,
											   [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt_Ad, 10)], kEmail,
											   nil]];						
					}
					
					[theAds addObject:theGroups];
				}
				
				sqlite3_finalize(stmt_Ad);
				sqlite3_free(sqlStmt_Ad);
			}
			
		} else {
			printf( "could not prepare statemnt: %s\n", sqlite3_errmsg(db) );
		}
		
	} else {
		printf( "could not prepare statemnt: %s\n", sqlite3_errmsg(db) );
	}
	
	sqlite3_finalize(stmt);
	sqlite3_free(sqlStmt);
	sqlite3_close(db);
}
*/

// Save the data for the next use.
- (void) updateDefaults
{
	[[NSUserDefaults standardUserDefaults] setObject:theAds    forKey:@"ad"];
	[[NSUserDefaults standardUserDefaults] setObject:theTitles forKey:@"title"];
	[[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)rebuild:(NSString *)str {
	
	theAds    = [[NSMutableArray alloc] init];
	theTitles = [[NSMutableArray alloc] init];
	NSString *ok=@"";
	NSString *nk=@"";
	BOOL ex = FALSE;
	NSMutableArray *theGroups;
	
	NSArray *ad = [str componentsSeparatedByString:@"!"];
	
	for (int i=0; i<[ad count]-1; i++) {
		
		NSString *s = [ad objectAtIndex:i];
	
		NSArray *m = [s componentsSeparatedByString:@"|"];

		nk=[m objectAtIndex:1];

		if (![nk isEqualToString:ok]) {
			[theTitles addObject:[m objectAtIndex:1]];
			//NSLog(@"%@", [m objectAtIndex:1]);
			ok=nk;
			ex=TRUE;
			theGroups = [[[NSMutableArray alloc] init] autorelease];
		}

		[theGroups addObject:[NSDictionary dictionaryWithObjectsAndKeys:
							  [m objectAtIndex:3], kCname,
							  [m objectAtIndex:2], kTeacher,
							  [m objectAtIndex:4], kCdate,
							  [m objectAtIndex:5], kCtime,
							  [m objectAtIndex:6], kFee,
							  [m objectAtIndex:7], kAddress,
							  [m objectAtIndex:8], kRemark,
							  [m objectAtIndex:9], kContact,
							  [m objectAtIndex:10], kEmail,
							  nil]];						
		
		if (ex==TRUE) {
			ex=FALSE;
			[theAds addObject:theGroups];
		}
	}

	[self updateDefaults];

	[self.tableView reloadData];
}


#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {

    [super viewDidLoad];

	// Load the saved data
	theAds    = [[NSUserDefaults standardUserDefaults] objectForKey:@"ad"];
	theTitles = [[NSUserDefaults standardUserDefaults] objectForKey:@"title"];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
	//[self initDB];
	
	//NSLog(@"AdController %d", theAds.count);

    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	// Add the edit button
	UIBarButtonItem	*backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" 
								style:UIBarButtonItemStylePlain target:nil action:nil];
	self.navigationItem.backBarButtonItem = backButton;

	UIBarButtonItem	*updateButton = [[UIBarButtonItem alloc] initWithTitle:@"更新" 
								style:UIBarButtonItemStylePlain target:self action:@selector(networkCheck:)];
	
	self.navigationItem.leftBarButtonItem = updateButton;

	// Setup UIActivityIndicatorView
	activityIndicator = [[UIActivityIndicatorView alloc] 
						 initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] ;
	activityIndicator.hidden = YES;
	[self.view addSubview:activityIndicator];
	activityIndicator.autoresizesSubviews = TRUE;
	activityIndicator.center = self.view.center;
	
}


#pragma mark -
#pragma mark Network Control
	
- (void)networkCheck:(id)sender {

 	[activityIndicator startAnimating];

	//BOOL wifi = [UIDevice wiFiConnected];
	BOOL eth  = [UIDevice networkConnected];
	BOOL cell = [UIDevice cellularConnected];
	BOOL wifi = [UIDevice wiFiConnected];
	
	UIAlertView *alert;
	NSString *whatType;
	BOOL state = TRUE;
	if (cell) {
		whatType = @"Cellular";
	} else if (eth) {
		whatType = @"EtheNet";
	} else if (wifi) {
		whatType = @"WiFi";
	} else {
		state = FALSE;
		whatType = @"fail";
		
	}

	if (state==FALSE) {
		
		NSString *disconnect = @"No network available !";
		alert = [[UIAlertView alloc] 
				initWithTitle:@"Sync" 
				message:disconnect 
				delegate:self 
				cancelButtonTitle:@"OK" 
				otherButtonTitles:nil];
		[alert show];
		[alert release];

		return;
	}
	NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseURL]];
	[req setTimeoutInterval:10.0];
	[req setHTTPMethod:@"POST"];
	
	NSHTTPURLResponse *returnResponse = nil;
	NSError *returnError = nil;
	NSData *returnData;
	@try {
		returnData = [NSURLConnection sendSynchronousRequest:req returningResponse:&returnResponse error:&returnError];
	}
	@catch (NSException *exception) {
		NSLog(@"main: Caught %@: %@", [exception name], [exception reason]);
	}
	@catch (id ue) {
		NSLog(@"%@", ue);
	}
	
	int statusCode = returnResponse.statusCode;
	NSString *str = [[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] autorelease];
	NSRange range = NSMakeRange (0, 4);
	NSString *code;
	if ([str length] > 4) {
		code = [str substringWithRange:range];
	} else {
		code = @"fail";
	}
	NSString *result;
	
	if([code isEqualToString:@"jack"] && (statusCode == 200) && !returnError){
		//[self.tableView reloadData];
		[self rebuild:str];
		result = @"Welcome to AoA !";
	}
	else{
		result = [NSString stringWithFormat:@"Failed to connect with error: %@.", returnError];
	}

	alert = [[UIAlertView alloc] 
			 initWithTitle:@"Sync" 
			 message:result 
			 delegate:self 
			 cancelButtonTitle:@"OK" 
			 otherButtonTitles:nil];
	[alert show];
	[alert release];
}


#pragma mark -
#pragma mark UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	[activityIndicator stopAnimating];
	//NSLog(@"UIAlertViewDelegate");
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	//NSLog(@"%d", [theAds count]);
    return [theAds count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    //return [[theAds objectAtIndex:section] count];
	//NSLog(@"%d %d", section, [[theAds objectAtIndex:section] count]);
	return [[theAds objectAtIndex:section] count];
	//return 0;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	//NSLog(@"%@", [theTitles objectAtIndex:section]);
	return [theTitles objectAtIndex:section];
}


- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
	return nil;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    // Configure the cell...
	cell.textLabel.text = [[[theAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:kCname];
	
	NSString *cdate = [[[theAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:kCdate];
	
	if ([cdate length] > 0) {
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - %@",
									 [[[theAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:kCdate],
									 [[[theAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:kTeacher]];
	} else {
		cell.detailTextLabel.text = [[[theAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:kTeacher];
	}

    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
    // Navigation logic may go here. Create and push another view controller.
	Advert *ad = [[Advert alloc] init];
	ad.title = [[[theAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:kTeacher];
	ad.theData = [[theAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	[self.navigationController pushViewController:ad animated:YES];
	[ad release];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
	//[self updateDefaults];
	theAds = nil;
	theTitles = nil;
	activityIndicator = nil;
}


- (void)dealloc {
	[theAds release];
	[theTitles release];
	[activityIndicator release];
    [super dealloc];
}


@end

